import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/task.dart';

class TaskStorageService {
  static const String _tasksKey = 'tasks';
  static TaskStorageService? _instance;
  
  TaskStorageService._internal();
  
  static TaskStorageService get instance {
    _instance ??= TaskStorageService._internal();
    return _instance!;
  }
  
  // 保存任务列表到本地存储
  Future<void> saveTasks(List<Task> tasks) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tasksJson = tasks.map((task) => task.toJson()).toList();
      final tasksString = jsonEncode(tasksJson);
      await prefs.setString(_tasksKey, tasksString);
      print('Tasks saved successfully: ${tasks.length} tasks');
    } catch (e) {
      print('Error saving tasks: $e');
    }
  }
  
  // 从本地存储加载任务列表
  Future<List<Task>> loadTasks() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tasksString = prefs.getString(_tasksKey);
      
      if (tasksString == null || tasksString.isEmpty) {
        print('No saved tasks found, returning empty list');
        return [];
      }
      
      final tasksJson = jsonDecode(tasksString) as List;
      final tasks = tasksJson.map((taskJson) => Task.fromJson(taskJson)).toList();
      print('Tasks loaded successfully: ${tasks.length} tasks');
      return tasks;
    } catch (e) {
      print('Error loading tasks: $e');
      return [];
    }
  }
  
  // 添加单个任务
  Future<void> addTask(Task task) async {
    try {
      final tasks = await loadTasks();
      tasks.add(task);
      await saveTasks(tasks);
      print('Task added: ${task.title}');
    } catch (e) {
      print('Error adding task: $e');
    }
  }
  
  // 更新任务
  Future<void> updateTask(Task updatedTask) async {
    try {
      final tasks = await loadTasks();
      final index = tasks.indexWhere((task) => task.id == updatedTask.id);
      if (index != -1) {
        tasks[index] = updatedTask;
        await saveTasks(tasks);
        print('Task updated: ${updatedTask.title}');
      }
    } catch (e) {
      print('Error updating task: $e');
    }
  }
  
  // 删除任务
  Future<void> deleteTask(String taskId) async {
    try {
      final tasks = await loadTasks();
      tasks.removeWhere((task) => task.id == taskId);
      await saveTasks(tasks);
      print('Task deleted: $taskId');
    } catch (e) {
      print('Error deleting task: $e');
    }
  }
  
  // 清空所有任务
  Future<void> clearAllTasks() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_tasksKey);
      print('All tasks cleared');
    } catch (e) {
      print('Error clearing tasks: $e');
    }
  }
} 